package com.laiyw.monitor.filter;

import com.laiyw.monitor.utils.ByteUtils;
import com.laiyw.monitor.utils.DateUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * @Description:
 * @Auther: Laiyw
 * @Date: 2018/10/4 9:37
 */
public class SystemOperationLogFilter implements Filter {

    private final Logger logger = Logger.getLogger("SystemOperationLogFilter");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;

        long beginTime = System.currentTimeMillis();
        logger.info("计时开始：" + DateUtils.formatDate(beginTime, DateUtils.HHMMSSSSS) + " URI：" + httpServletRequest.getRequestURI());

        System.out.println("getContextPath--->" + httpServletRequest.getContextPath());
        System.out.println("getServletPath--->" + httpServletRequest.getServletPath());
        System.out.println("getRequestURI--->" + httpServletRequest.getRequestURI());
        chain.doFilter(request, response);

        long endTime = System.currentTimeMillis();
        long executeTime = endTime - beginTime;
        Runtime runtime = Runtime.getRuntime();
        logger.info("计时结束：" + DateUtils.formatDate(endTime, DateUtils.HHMMSSSSS) + " 用时：" + DateUtils.formatDateAgo(executeTime) + " 总内存：" + ByteUtils.formatByteSize(runtime.totalMemory()) + " 已用内存：" + ByteUtils.formatByteSize(runtime.totalMemory() - runtime.freeMemory()));

    }

    @Override
    public void destroy() {

    }
}
